import type { SSEHandler } from './index'
import { http, HttpClient } from './index'

/**
 * HTTP请求使用示例
 */
export class HttpExample {
  /**
   * 普通HTTP请求示例
   */
  public static async demonstrateHttpRequests(): Promise<void> {
    try {
      // GET请求示例
      const users = await http.get('/api/users')
      console.log('GET请求结果:', users)

      // POST请求示例
      const newUser = await http.post('/api/users', {
        name: 'John Doe',
        email: 'john@example.com',
      })
      console.log('POST请求结果:', newUser)

      // PUT请求示例
      const updatedUser = await http.put('/api/users/1', {
        name: 'John Updated',
      })
      console.log('PUT请求结果:', updatedUser)

      // DELETE请求示例
      const result = await http.delete('/api/users/1')
      console.log('DELETE请求结果:', result)
    } catch (error) {
      console.error('HTTP请求错误:', error)
    }
  }

  /**
   * SSE请求示例
   */
  public static demonstrateSSE(): void {
    const sseHandlers: SSEHandler = {
      onMessage: (event: MessageEvent) => {
        console.log('📨 收到SSE消息:', event.data)
        try {
          const data = JSON.parse(event.data)
          console.log('解析后的数据:', data)
        } catch (e) {
          console.log('原始消息数据:', event.data)
        }
      },
      onOpen: (event: Event) => {
        console.log('🔗 SSE连接已建立')
      },
      onError: (event: Event) => {
        console.error('❌ SSE连接错误:', event)
      },
      onClose: (event: Event) => {
        console.log('🚪 SSE连接已关闭')
      },
    }

    // 创建SSE连接
    const eventSource = http.createSSE('/api/events', sseHandlers)

    // 可以保存eventSource以便后续关闭
    // setTimeout(() => {
    //   eventSource.close();
    //   console.log('手动关闭SSE连接');
    // }, 10000);
  }

  /**
   * 自定义HTTP客户端示例
   */
  public static demonstrateCustomClient(): void {
    // 创建自定义配置的HTTP客户端
    const customHttp = new HttpClient('https://api.example.com', {
      timeout: 15000,
      headers: {
        'X-Custom-Header': 'custom-value',
      },
    })

    // 设置认证token
    customHttp.setAuthToken('your-auth-token-here')

    // 使用自定义客户端
    customHttp
      .get('/v1/data')
      .then((data) => console.log('自定义客户端请求结果:', data))
      .catch((error) => console.error('自定义客户端错误:', error))
  }
}

// 使用示例
// HttpExample.demonstrateHttpRequests();
// HttpExample.demonstrateSSE();
// HttpExample.demonstrateCustomClient();
